package cn.study.cas.unsafe;

import org.openjdk.jol.info.ClassLayout;
import sun.misc.Unsafe;

/**
 * @Author     ：跟大佳一起学架构
 * @Description：如何实现一个cas
 */
public class AtomicTeacherAgeUpdater {
    private String name ;
    private volatile int age;
    public AtomicTeacherAgeUpdater(String name, int age){
        this.name = name;
        this.age = age;
    }
    public int getAge(){
        return this.age;
    }
    public static void main(String[] args) {
        AtomicTeacherAgeUpdater updater = new AtomicTeacherAgeUpdater("大佳",18);
        System.out.println(ClassLayout.parseInstance(updater).toPrintable());
        updater.compareAndSwapAge(17,18);
        System.out.println("大佳的真实年龄---"+updater.getAge());
    }
    private static final Unsafe unsafe = UnsafeInstance.reflectGetUnsafe();
    private static final long valueOffset;
    static {
        try {
            // 获取对象中字段的偏移量
            valueOffset = unsafe.objectFieldOffset(AtomicTeacherAgeUpdater.class.getDeclaredField("age"));
            System.out.println("valueOffset:--->"+valueOffset);
        } catch (Exception e) {
            throw new Error(e);
        }
    }
    public void compareAndSwapAge(int old,int target){
        unsafe.compareAndSwapInt(this,valueOffset,old,target);
    }
}
